package com.example.typhoonproject.controller;

import com.example.typhoonproject.common.utils.Util;
import com.example.typhoonproject.entity.TyphoonPointEntity;
import com.example.typhoonproject.service.TyphoonPointService;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 解析CSV文件，入库高分辨率实时台风表（计算入库）
 */
@Slf4j
@Component
public class TyphoonCsvTask {

    @Autowired
    private TyphoonPointService typhoonPointService;

    @Value("${dataConfig.csvFilPath}")
    private String csvFilPath;

    private volatile boolean isTaskRunning = false;

    private ScheduledExecutorService exec;

    public void myTask(String code) {
        log.info("调用解析csv文件线程.....{}", isTaskRunning);
        if (isTaskRunning) {
            return;
        }
        isTaskRunning = true;
        // 创建线程池
        exec = Executors.newScheduledThreadPool(5);
        // 每隔10分钟读取一次的入库文件
        exec.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                log.info("调用台风入库线程.....");
                try {
                    typhoonstorage(code);
                } catch (Exception e) {
                    log.error("调用台风入库线程启动发生异常: {}", e.getMessage());
                }
            }
        }, 0, 1, TimeUnit.MINUTES);
    }

    public synchronized void stopTask() {
        if (isTaskRunning && exec != null) {
            exec.shutdown();
            isTaskRunning = false;
            log.info("台风入库线程已停止。");
        }
    }

    private void typhoonstorage(String code) {

        //String filePath = "D:\\remaps_data2\\202305_v1_0.csv";
        // 拼接文件路径
        String fileName = code + "_v2_0.csv";
        String filePath = String.format("%s%s%s", csvFilPath, File.separator, fileName);

        if (!Files.exists(Paths.get(filePath))) {
            //System.out.println("文件不存在: " + filePath);
            log.info("文件不存在:{}.....", filePath);
            return;
        }
        log.info("开始读取csv文件:{}.....", filePath);
        //String code = filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.lastIndexOf("\\") + 7);
        List<String> existingTyTimes = typhoonPointService.findTyTimesByCode(code);
        List<TyphoonPointEntity> typhoonEntities = new ArrayList<>();

        try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
            String[] line;
            boolean isFirstLine = true;

            while ((line = reader.readNext()) != null) {
                if (isFirstLine) {
                    isFirstLine = false;
                    continue; // 跳过第一行
                }

                String tyTime = line[0];
                if (existingTyTimes.contains(formatTyTime(tyTime))) {
                    continue; // 跳过已存在的 tyTime
                }

                TyphoonPointEntity typhoonPointEntity = new TyphoonPointEntity();
                typhoonPointEntity.setCode(code);
                typhoonPointEntity.setTyTime(tyTime);
                typhoonPointEntity.setTyTime(formatTyTime(tyTime));
                typhoonPointEntity.setLati(parseDoubleOrDefault(line[1]));
                typhoonPointEntity.setLoni(parseDoubleOrDefault(line[2]));
                typhoonPointEntity.setEnpre(parseDoubleOrDefault(line[4]));
                typhoonPointEntity.setMaxwp(parseDoubleOrDefault(line[5]));
                typhoonPointEntity.setIntensity(Util.getIntensity(parseDoubleOrDefault(line[5])));
                typhoonPointEntity.setRadii(parseDoubleOrDefault(line[6]));
                typhoonPointEntity.setRadius7_ne(parseDoubleOrDefault(line[13]));
                typhoonPointEntity.setRadius7_se(parseDoubleOrDefault(line[14]));
                typhoonPointEntity.setRadius7_sw(parseDoubleOrDefault(line[15]));
                typhoonPointEntity.setRadius7_nw(parseDoubleOrDefault(line[16]));
                typhoonPointEntity.setRadius10_ne(parseDoubleOrDefault(line[17]));
                typhoonPointEntity.setRadius10_se(parseDoubleOrDefault(line[18]));
                typhoonPointEntity.setRadius10_sw(parseDoubleOrDefault(line[19]));
                typhoonPointEntity.setRadius10_nw(parseDoubleOrDefault(line[20]));
                typhoonPointEntity.setRadius12_ne(parseDoubleOrDefault(line[21]));
                typhoonPointEntity.setRadius12_se(parseDoubleOrDefault(line[22]));
                typhoonPointEntity.setRadius12_sw(parseDoubleOrDefault(line[23]));
                typhoonPointEntity.setRadius12_nw(parseDoubleOrDefault(line[24]));
                log.info("保存台风数据成功:{}.....", typhoonPointEntity);

                typhoonEntities.add(typhoonPointEntity);
            }

            if (!typhoonEntities.isEmpty()) {
                typhoonPointService.saveBatch(typhoonEntities); // 批量保存到数据库
            }

        } catch (IOException | CsvValidationException | ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 台风时间转换为 “yyyyMMddHHmmss”
     *
     * @param tyTime
     * @return
     * @throws ParseException
     */
    private String formatTyTime(String tyTime) throws ParseException {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd_HHmm");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return outputFormat.format(inputFormat.parse(tyTime));
    }

    /**
     * 解析字符串为 Double 类型，如果字符串为空或无效，则返回 0
     *
     * @param value
     * @return
     */
    private Double parseDoubleOrDefault(String value) {
        try {
            return (value == null || value.isEmpty() || value.equalsIgnoreCase("nan")) ? 0.0 : Double.parseDouble(value);
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    /**
     * 解析字符串为 Integer 类型，如果字符串为空或无效，则返回 0
     *
     * @param value
     * @return
     */
    private Integer parseIntOrDefault(String value) {
        try {
            return (value == null || value.isEmpty() || value.equalsIgnoreCase("nan")) ? 0 : Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return 0;
        }
    }
}
